package com.tanhua.dubbo.api;

import cn.hutool.core.collection.CollUtil;
import com.tanhua.dubbo.utils.IdWorker;
import com.tanhua.dubbo.utils.TimeLineService;
import com.tanhua.model.mongo.Movement;
import com.tanhua.model.mongo.MovementTimeLine;
import com.tanhua.model.vo.PageResult;
import org.apache.dubbo.config.annotation.DubboService;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationResults;
import org.springframework.data.mongodb.core.aggregation.TypedAggregation;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;

import java.util.List;

@DubboService
public class MovementApiImpl implements MovementApi {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private TimeLineService timeLineService;

    @Autowired
    private IdWorker idWorker;

    //
    @Override
    public String pushlish(Movement movement) {
        //mongodb不支持自动增长
        //保存动态详情   张三  -  发布了动态  -- 1
        movement.setPid(idWorker.getNextId("movement"));
        mongoTemplate.save(movement);
        //根据当前用户的id查询好友数据   List<Friend>   张三：  李四，王五
        //调用工具，异步保存timeline数据
        timeLineService.saveTimeLine(movement.getId(),movement.getUserId());
        return movement.getId().toHexString();
    }

    //根据用户id，查询动态详情列表数据
    public List<Movement> findByUserId(Long userId, Integer page, Integer pagesize) {
        //构建Criteria
        Criteria criteria = Criteria.where("userId").is(userId).and("state").is(1);
        //构建Query
        Query query = Query.query(criteria).with(Sort.by(Sort.Order.desc("created")))
                .skip((page - 1) * pagesize).limit(pagesize);
        //查询
        return mongoTemplate.find(query,Movement.class);
    }

    //根据用户id，查询用户好友发布的动态列表数据
    public List<Movement> findFriendMovements(Long userId, Integer page, Integer pagesize) {
        //1、根据FriendId查询时间线表 List<MovementTimeLine>
        Criteria criteria = Criteria.where("friendId").is(userId);
        Query query = Query.query(criteria).with(Sort.by(Sort.Order.desc("created")))
                .skip((page - 1) * pagesize).limit(pagesize);
        List<MovementTimeLine> list = mongoTemplate.find(query, MovementTimeLine.class);
        //2、提取所有可查看的动态id集合   List<ObjectId>: 1,2,3,4,5,6
        List<ObjectId> ids = CollUtil.getFieldValues(list, "movementId", ObjectId.class);
        //3、根据动态id集合以 in的方式查询所有动态
        Criteria movementCriteria = Criteria.where("id").in(ids).and("state").is(1);
        Query movementQuery = Query.query(movementCriteria);
        return mongoTemplate.find(movementQuery,Movement.class);
    }

    //随机获取指定条数的动态
    public List<Movement> randomMovements(int count) {
        //设置统计函数
        TypedAggregation<Movement> aggregation =
                TypedAggregation.newAggregation(Movement.class, Aggregation.sample(count));//随机获取

        //统计查询：将查询结果封装到了AggregationResults中
        AggregationResults<Movement> results = mongoTemplate.aggregate(aggregation, Movement.class);

        //获取数据
        return results.getMappedResults();
    }

    //根据pid查询动态详情
    public List<Movement> findByPids(List<Long> pids) {
        Criteria criteria = Criteria.where("pid").in(pids);
        Query query = Query.query(criteria);
        return mongoTemplate.find(query,Movement.class);
    }

    //根据动态id查询动态
    public Movement findById(String id) {
        return mongoTemplate.findById(new ObjectId(id),Movement.class);
    }

    //根据条件查询动态
    public PageResult findMovement(Long userId, Integer state, int page, int pagesize) {
        //1、构建query对象
        Query query = new Query();
        if(userId != null) {
            query.addCriteria(Criteria.where("userId").is(userId));
        }
        if(state != null) {
            query.addCriteria(Criteria.where("state").is(state));
        }
        //2、查询总数
        long count = mongoTemplate.count(query, Movement.class);
        //3、查询列表
        query.with(Sort.by(Sort.Order.desc("created")))
                .skip((page-1) * pagesize)
                .limit(pagesize);
        List<Movement> list = mongoTemplate.find(query, Movement.class);
        return new PageResult(page,pagesize,count,list);
    }

    @Override
    public void updateState(String movementId, int state) {
        Query query = Query.query(Criteria.where("id").in(new ObjectId(movementId)));
        Update update = Update.update("state", state);
        mongoTemplate.updateFirst(query,update,Movement.class);
    }
}
